package com.remist.dao.impl.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.remist.common.PaginationSupport;
import com.remist.dao.impl.MemberDao;
import com.remist.model.Member;

public class MemberDaoImpl extends JpaDaoSupport implements MemberDao {

	public void addMember(Member bean) {
		getJpaTemplate().persist(bean);
	}

	public void updateMember(Member bean) {
		getJpaTemplate().merge(bean); 
	}

	public void deleteMember(Member bean) {
		Member findBean = getJpaTemplate().find(Member.class, bean.getId());
        if (findBean != null)
        {
            getJpaTemplate().remove(findBean);
        }
		 
	}

	public Member getMemberById(Member bean) {
		 return getJpaTemplate().find(Member.class, bean.getId());
	}
	
	public PaginationSupport getPaginationSupport(int pageSize,int startIndex ){
		EntityManager em = getJpaTemplate().getEntityManagerFactory().createEntityManager();
		Query rowCountQuery =  em.createQuery(" SELECT COUNT(m) FROM Member m ");
		int totalCount =((Long) rowCountQuery.getSingleResult()).intValue();
		final Query getRowsQuery = em.createQuery(" SELECT m FROM Member m  ");
		getRowsQuery.setMaxResults(pageSize).setFirstResult(startIndex);
		List <Member> resultList = getRowsQuery.getResultList();
//		List items, int totalCount, int pageSize, int startIndex
		PaginationSupport  ps = new PaginationSupport(resultList,totalCount,pageSize,startIndex);
		return ps;
	}

	@Override
	public Member checkEmailAndPassword(Member member) {
		List<Member> find = getJpaTemplate().find(" SELECT  m FROM Member m WHERE m.email='"+member.getEmail()+"' AND  m.passwd='"+member.getPasswd()+"'" );
		if ( find != null && find.size()>0 )
			return find.get(0);
		else 
			return null;
	}
}
